package com.hzcx.app.simplechat.ui.moment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.ui.moment.adapter.MomentCommentAdapter;
import com.hzcx.app.simplechat.ui.moment.bean.MomentCommentBean;
import com.hzcx.app.simplechat.ui.moment.bean.MomentInfoBean;
import com.hzcx.app.simplechat.ui.moment.contract.MomentInfoContract;
import com.hzcx.app.simplechat.ui.moment.dialog.MomentCommentDialog;
import com.hzcx.app.simplechat.ui.moment.event.DeleteCommentEvent;
import com.hzcx.app.simplechat.ui.moment.event.DeleteMomentEvent;
import com.hzcx.app.simplechat.ui.moment.presenter.MomentInfoPresenter;
import com.hzcx.app.simplechat.ui.moment.util.CenterAlignImageSpan;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.setting.ReportActivity;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.app.AppHelper;
import com.hzcx.app.simplechat.util.dp.DpUtils;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.view.CommentTextView;
import com.hzcx.app.simplechat.view.FabulousTextView;
import com.hzcx.app.simplechat.view.autogridview.PhotoLoader;
import com.hzcx.app.simplechat.view.imageview.RoundImageView;
import com.liyi.grid.AutoGridView;
import com.liyi.grid.adapter.SimpleAutoGridAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import indi.liyi.viewer.ImageViewer;

/**
 * 动态详情
 */
public class MomentInfoActivity extends BaseActivity<MomentInfoPresenter> implements MomentInfoContract.View, OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemChildClickListener {

    public static final String INTENT_MOMENT_ID = "INTENT_MOMENT_ID";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.rv_comment)
    RecyclerView rvComment;
    @BindView(R.id.ll_comment)
    LinearLayout llComment;
    @BindView(R.id.imageViewer)
    ImageViewer imageViewer;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;


    private int momentId;

    private List<MomentCommentBean> commentData;
    private MomentCommentAdapter commentAdapter;

    private TextView tvNickName;
    private RoundImageView ivHead;
    private TextView tvDate;
    private FabulousTextView tvFabulous;
    private TextView tvFabulousPeople;
    private TextView tvContent;
    private CommentTextView tvComment;
    private AutoGridView rvImgs;
    private StandardGSYVideoPlayer videoPlayer;

    private int page = 1;
    private boolean isRefresh = true;

    private MomentInfoBean momentInfoBean;

    @Override
    public int getLayout() {
        return R.layout.activity_moment_info;
    }

    @Override
    public void initPresenter() {
        mPresenter = new MomentInfoPresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText("动态");
        ivTitleRight.setImageResource(R.mipmap.ic_icon_title_more);

        commentData = new ArrayList<>();
        commentAdapter = new MomentCommentAdapter(commentData);
        rvComment.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvComment.setAdapter(commentAdapter);

        imageViewer.imageLoader(new PhotoLoader());

        // 评论列表点击
        commentAdapter.setOnItemClickListener((adapter, view, position) ->
                showCommentDialog(commentData.get(position).getReview_id() + ""));

        commentAdapter.setOnItemChildClickListener(this);

        smartRefresh.setOnRefreshListener(this);
        commentAdapter.setOnLoadMoreListener(this);
    }

    @Override
    public void initData() {
        momentId = getIntent().getIntExtra(INTENT_MOMENT_ID, 0);
        mPresenter.getMomentInfo(this, momentId);

        mPresenter.getMomentCommentList(this, momentId, page);
    }

    @OnClick({R.id.ll_comment, R.id.iv_title_right})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.ll_comment: // 评论
                showCommentDialog(null);
                break;

            case R.id.iv_title_right: // 更多
                showMoreDialog();
                break;
        }
    }

    /**
     * 点击列表更多选项
     */
    private void showMoreDialog() {
        List<String> str = new ArrayList<>();
        if (momentInfoBean.getDynamic_data().getMember_id() == UserInfoUtil.getUserId()) {
            // 操作自己的动态
            str.add("删除动态");
        } else {
            // 操作别人的动态
            str.add("举报");
            str.add("屏蔽此动态");
        }

        PublicRoundDialog roundDialog = new PublicRoundDialog(this, "请选择", str, (pos1, menu) -> {
            switch (menu) {
                case "删除动态":
                    mPresenter.deleteMoment(MomentInfoActivity.this, momentInfoBean.getDynamic_data().getDynamic_id());
                    break;

                case "举报":
                    startActivity(new Intent(MomentInfoActivity.this, ReportActivity.class)
                            .putExtra(ReportActivity.INTENT_USER_ID, momentInfoBean.getDynamic_data().getMember_id()));
                    break;

                case "屏蔽此动态":
                    mPresenter.shieldMoment(MomentInfoActivity.this, momentInfoBean.getDynamic_data().getDynamic_id());
                    break;
            }
        });
        roundDialog.show();
    }


    /**
     * 弹出评论弹窗
     *
     * @param commentId
     */
    private void showCommentDialog(String commentId) {
        MomentCommentDialog commentDialog = new MomentCommentDialog(this, commentId, (comment, id) ->
                mPresenter.momentComment(MomentInfoActivity.this, momentId, comment, id));
        commentDialog.show();
    }

    /**
     * 获取动态详情成功
     *
     * @param data
     */
    @Override
    public void momentInfoResult(MomentInfoBean data) {
        momentInfoBean = data;
        View view = LayoutInflater.from(this).inflate(R.layout.layout_moment_info_header, null);
        tvNickName = view.findViewById(R.id.tv_nick_name);
        ivHead = view.findViewById(R.id.iv_head);
        tvDate = view.findViewById(R.id.tv_date);
        tvFabulous = view.findViewById(R.id.tv_fabulous);
        tvFabulousPeople = view.findViewById(R.id.tv_fabulous_people);
        tvComment = view.findViewById(R.id.tv_commont);
        tvContent = view.findViewById(R.id.tv_content);
        rvImgs = view.findViewById(R.id.rv_img);
        videoPlayer = view.findViewById(R.id.videoPlayer);

        if (data.getDynamic_data().getType() == 2) {
            tvNickName.setText(data.getDynamic_data().getAd_name());
            GlideUtils.loadImg(this, data.getDynamic_data().getAd_logo(), ivHead);
        } else {
            tvNickName.setText(data.getDynamic_data().getNickname());
            GlideUtils.loadImg(this, data.getDynamic_data().getAvatar(), ivHead);
        }
        tvDate.setText(data.getDynamic_data().getCreatetime());
        tvFabulous.setFabulousNum(data.getDynamic_data().getGreatcount());
        tvFabulous.setIsFabulous(data.getDynamic_data().getGreatstate());
        tvComment.setFabulousNum(data.getDynamic_data().getReviewcount());
        tvComment.setIsComment(data.getDynamic_data().getReviewstate());
        String s = "";
        for (int i = 0; i < data.getGreat_data().size(); i++) {
            s += data.getGreat_data().get(i).getNickname() + "    ";
        }
        tvFabulousPeople.setText(s);

        // 设置内容
        if (EmptyUtils.isEmpty(data.getDynamic_data().getLinkurl())) {
            // 如果没有链接，直接设置内容
            tvContent.setText(data.getDynamic_data().getMaincontent());
        } else {
            // 有链接，添加网页链接字样
            String content = data.getDynamic_data().getMaincontent();
            String str = content.substring(0, data.getDynamic_data().getSubscript()) + "网页链接" + content.substring(data.getDynamic_data().getSubscript());
            SpannableString sps = new SpannableString(str);
            Drawable drawable = getResources().getDrawable(R.mipmap.ic_icon_moment_http_text);
            drawable.setBounds(0, 0, DpUtils.dp2px(this, 80), DpUtils.dp2px(this, 15));
            //居中对齐imageSpan
            CenterAlignImageSpan imageSpan = new CenterAlignImageSpan(drawable);
            sps.setSpan(imageSpan, data.getDynamic_data().getSubscript(), data.getDynamic_data().getSubscript() + 4, ImageSpan.ALIGN_BASELINE);
            tvContent.setText(sps);
        }

        setImgs(rvImgs, data.getDynamic_data().getDy_images());

        // 点赞
        tvFabulous.setOnClickListener(view1 -> mPresenter.momentFabulous(MomentInfoActivity.this, momentId));

        // 评论
        tvComment.setOnClickListener(view12 -> showCommentDialog(null));

        // 设置视频
        if (EmptyUtils.isNotEmpty(data.getDynamic_data().getVideofile())) {
            // 动态设置播放器宽高
            ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) videoPlayer.getLayoutParams();
            int videoMaxWidth = 850;
            if (data.getDynamic_data().getVideo_cover_width() > videoMaxWidth) {
                params.width = videoMaxWidth;
            } else {
                params.width = data.getDynamic_data().getVideo_cover_width();
            }
            params.height = data.getDynamic_data().getVideo_cover_height();
            LogUtils.d("宽：" + data.getDynamic_data().getVideo_cover_width() + "    高：" + data.getDynamic_data().getVideo_cover_height());
            videoPlayer.setLayoutParams(params);
            videoPlayer.setVisibility(View.VISIBLE);

            ImageView imageView = new ImageView(this);
            GlideUtils.loadImg(this, data.getDynamic_data().getVideo_cover(), imageView);

            videoPlayer.setThumbImageView(imageView);
            videoPlayer.setIsTouchWiget(false);
            videoPlayer.setUp(data.getDynamic_data().getVideofile(), true, "");
            videoPlayer.setRotateViewAuto(true);
            videoPlayer.setTag(TAG);
            videoPlayer.setReleaseWhenLossAudio(true);
            videoPlayer.setVideoAllCallBack(new GSYSampleCallBack() {
                @Override
                public void onPrepared(String url, Object... objects) {
                    super.onPrepared(url, objects);
                    GSYVideoManager.instance().setNeedMute(true);
                }

                @Override
                public void onQuitFullscreen(String url, Object... objects) {
                    super.onQuitFullscreen(url, objects);
                    GSYVideoManager.instance().setNeedMute(true);
                }

                @Override
                public void onEnterFullscreen(String url, Object... objects) {
                    super.onEnterFullscreen(url, objects);
                    GSYVideoManager.instance().setNeedMute(false);
                }
            });

            videoPlayer.getBackButton().setVisibility(View.GONE);
            videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    videoPlayer.startWindowFullscreen(MomentInfoActivity.this, false, true);
                }
            });

            videoPlayer.startPlayLogic();
            rvImgs.setVisibility(View.GONE);
        }

        commentAdapter.addHeaderView(view);
        commentAdapter.notifyDataSetChanged();
    }

    /**
     * 评论成功
     *
     * @param data
     */
    @Override
    public void commentSuccess(MomentCommentBean data) {
        commentData.add(0, data);
        commentAdapter.notifyDataSetChanged();

        // 更新UI
        momentInfoBean.getDynamic_data().setReviewstate(1);
        momentInfoBean.getDynamic_data().setGreatcount(momentInfoBean.getDynamic_data().getReviewcount() + 1);
    }

    /**
     * 评论列表获取成功
     *
     * @param data
     */
    @Override
    public void commentResult(List<MomentCommentBean> data) {
        smartRefresh.finishRefresh();
        commentAdapter.loadMoreComplete();
        try {
            if (isRefresh) {
                commentData.clear();
            }
            commentData.addAll(data);
            commentAdapter.notifyDataSetChanged();
            if (data.size() < Common.PAGE_COUNT) {
                commentAdapter.loadMoreEnd();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFail() {
        smartRefresh.finishRefresh();
        commentAdapter.loadMoreFail();
    }

    /**
     * 点赞成功
     */
    @Override
    public void fabulousSuccess() {
        if (momentInfoBean.getDynamic_data().getGreatstate() == 0) {
            momentInfoBean.getDynamic_data().setGreatstate(1);
            momentInfoBean.getDynamic_data().setGreatcount(momentInfoBean.getDynamic_data().getGreatcount() + 1);
            MomentInfoBean.GreatDataBean bean = new MomentInfoBean.GreatDataBean();
            bean.setNickname(UserInfoUtil.getUserNickName());
            bean.setMember_id(UserInfoUtil.getUserId());
            momentInfoBean.getGreat_data().add(bean);
        } else {
            momentInfoBean.getDynamic_data().setGreatstate(0);
            momentInfoBean.getDynamic_data().setGreatcount(momentInfoBean.getDynamic_data().getGreatcount() - 1);
            for (int i = 0; i < momentInfoBean.getGreat_data().size(); i++) {
                if (momentInfoBean.getGreat_data().get(i).getNickname().equals(UserInfoUtil.getUserNickName())) {
                    momentInfoBean.getGreat_data().remove(i);
                }
            }
        }
        tvFabulous.setFabulousNum(momentInfoBean.getDynamic_data().getGreatcount());
        tvFabulous.setIsFabulous(momentInfoBean.getDynamic_data().getGreatstate());

        String s = "";
        for (int i = 0; i < momentInfoBean.getGreat_data().size(); i++) {
            s += momentInfoBean.getGreat_data().get(i).getNickname() + "    ";
        }
        tvFabulousPeople.setText(s);
    }

    /**
     * 删除动态成功
     */
    @Override
    public void deleteSuccess() {
        showError("删除成功");
        EventBus.getDefault().post(new DeleteMomentEvent(momentInfoBean.getDynamic_data().getDynamic_id()));
        finish();
    }

    /**
     * 删除评论成功
     *
     * @param pos
     */
    @Override
    public void deleteCommentSuccess(int pos) {
        showError("删除成功");
        EventBus.getDefault().post(new DeleteCommentEvent(momentInfoBean.getDynamic_data().getDynamic_id()));
        commentData.remove(pos);
        commentAdapter.notifyDataSetChanged();
        momentInfoBean.getDynamic_data().setReviewcount(momentInfoBean.getDynamic_data().getReviewcount() - 1);
        tvComment.setFabulousNum(momentInfoBean.getDynamic_data().getReviewcount());
    }

    /**
     * 屏蔽动态成功
     *
     * @param id
     */
    @Override
    public void shieldSuccess(int id) {
        EventBus.getDefault().post(new DeleteMomentEvent(id));
        showError("屏蔽成功");
        finish();
    }

    /**
     * 设置展示的 图片
     *
     * @param rvImgs
     */
    private void setImgs(AutoGridView rvImgs, List<MomentInfoBean.DynamicDataBean.DyImagesBean> imgUrls) {
        List<String> imgs = new ArrayList<>();
        List<String> imgsBig = new ArrayList<>();
        if (imgUrls != null && imgUrls.size() > 0) {
            for (MomentInfoBean.DynamicDataBean.DyImagesBean bean : imgUrls) {
                imgs.add(bean.getImgurl());
                imgsBig.add(bean.getReal_imgurl());
            }
        }

        SimpleAutoGridAdapter adapter = new SimpleAutoGridAdapter();
        adapter.setSource(imgs);
        adapter.setImageLoader((position, source, view, viewType) -> GlideUtils.loadImgSimple(this, source.toString(), view));
        rvImgs.setOnItemClickListener((i, view) -> {
            imageViewer.overlayStatusBar(true)
                    .imageData(imgsBig)
                    .bindViewGroup(rvImgs)
                    .watch(i);
        });
        rvImgs.setGridOneHpercent(0.65f);
        rvImgs.setGridOneWpercent(0.65f);
        rvImgs.setAdapter(adapter);
        if (EmptyUtils.isEmpty(imgs) || imgs.size() <= 0) {
            rvImgs.setVisibility(View.GONE);
            return;
        } else {
            rvImgs.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        page++;
        isRefresh = false;
        mPresenter.getMomentCommentList(this, momentId, page);
    }

    /**
     * 刷新
     *
     * @param refreshLayout
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        isRefresh = false;
        mPresenter.getMomentCommentList(this, momentId, page);
    }

    /**
     * 列表子控件点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.iv_more: // 列表-更多
                showItemMoreDialog(position);
                break;
        }
    }

    /**
     * 点击列表更多选项
     */
    private void showItemMoreDialog(int pos) {
        List<String> str = new ArrayList<>();
        if (commentData.get(pos).getMember_id() == UserInfoUtil.getUserId()) {
            // 操作自己的动态
            str.add("删除评论");
        } else {
            // 操作别人的动态
            str.add("举报");
            str.add("屏蔽此动态");
        }

        PublicRoundDialog roundDialog = new PublicRoundDialog(this, "请选择", str, (pos1, menu) -> {
            switch (menu) {
                case "删除评论":
                    mPresenter.deleteComment(MomentInfoActivity.this, commentData.get(pos).getReview_id(), pos);
                    break;

                case "举报":

                    break;

                case "屏蔽此动态":

                    break;
            }
        });
        roundDialog.show();
    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean b = imageViewer.onKeyDown(keyCode, event);
        if (b) {
            return b;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }
}
